package com.suli.account.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.scenic.util.JWTUtils;
import com.scenic.util.ResponseResult;
import com.suli.account.entity.User;
import com.suli.account.entity.UserRole;
import com.suli.account.enums.UserType;
import com.suli.account.service.EmailService;
import com.suli.account.service.UserRoleService;
import com.suli.account.service.UserService;
import com.suli.account.util.Captcha;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.websocket.server.PathParam;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author SuLi
 * @since 2022-03-19
 */
@RestController
@CrossOrigin
@SuppressWarnings("all")
@Slf4j
@RequestMapping("/user")
public class UserController {
    @Autowired
    EmailService emailService;
    @Autowired
    UserService userService;
    @Autowired
    UserRoleService roleService;

    /**
     * 注册
     * @param user 实体类接收请求体
     * @return 返回注册结果
     */
    @PostMapping("/register")
    public ResponseResult register(@RequestBody User user) {
        Map<String, Integer> map = userService.registerUser(user);
        String resultMessage="";
        Integer registerStatus = map.get("registerStatus");
        switch (registerStatus){
            case 0: resultMessage="用户名已存在";break;
            case 1: resultMessage="邮箱已被注册";break;
            case 2: resultMessage="注册成功";break;
        }
        if(registerStatus<2)
        return ResponseResult.error().message(resultMessage);
        return ResponseResult.ok().message(resultMessage);
    }

    /**
     * 获取验证码
     * @param email 邮箱地址
     * @return 返回验证码给前台进行验证
     */
    @GetMapping("/getCaptcha/{email}")
    public ResponseResult getCaptcha(@PathVariable String email){
        String captcha = Captcha.getCaptcha();
        String content="您本次操作的验证码是："+captcha;
        emailService.sendSimpleMail(email, "云水旅游景区", content);
        log.info("发送验证码成功");
        return ResponseResult.ok().message("邮件发送成功").data("verify",captcha);
        //return ResponseResult.ok().message("邮件发送成功").data("verify","123");
    }

    /**
     * 登录账号
     * @return 返回token
     */
    @GetMapping("/login")
    public ResponseResult login(@PathParam("accountName") String accountName,
                                @PathParam("password") String password){
        log.info("账户：{}，密码：{}",accountName,password);
        Map<String, String> login = userService.login(accountName, password);
        if (login.get("message").equals("登录成功")){
            return ResponseResult.ok().message(login.get("message")).data("token",login.get("token"));
        }
        return ResponseResult.error().message(login.get("message"));
    }

    /**
     *通过解析token获取用户信息
     * @param token 令牌
     * @return 用户信息
     */
    @GetMapping("/getInfo")
    public ResponseResult getuserInfo(@RequestHeader("Scenic-Token") String token){
        Map<String, Object> info = JWTUtils.getInfo(token);
        if(!ObjectUtils.isEmpty(info))
            return ResponseResult.ok().data(info);
        return ResponseResult.error().message("获取用户信息失败");
    }

    /**
     * 重置密码
     * @param email 邮箱地址
     * @param newPassword 新密码
     * @return
     */
    @PutMapping("/resetPassword/{email}/{newPassword}")
    public ResponseResult resetPassword(@PathVariable String email,@PathVariable String newPassword){
        log.info("{}{}",email,newPassword);
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("user_email", email);
        User user = userService.getOne(queryWrapper);
        if(ObjectUtils.isEmpty(user)){
            return ResponseResult.error().message("此邮箱还未注册，请先注册");
        }
        UpdateWrapper<User> updateWrapper=new UpdateWrapper<>();
        String passwordSa = DigestUtils.md5DigestAsHex(newPassword.getBytes(StandardCharsets.UTF_8));
        updateWrapper.set("user_password", passwordSa).eq("user_email", email);
        boolean update = userService.update(updateWrapper);
        if(update)
        return ResponseResult.ok().message("重置密码成功");
        return ResponseResult.ok().message("注册异常，请稍后重试");
    }

    /**
     * 判断用户是否存在
     * @param name
     * @param email
     * @return
     */
    @GetMapping("/isExistUser/{name}/{email}")
    public ResponseResult isExist(@PathVariable String name, @PathVariable String email){
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("user_name", name).eq("user_email", email);
        User user = userService.getOne(queryWrapper);
        if(ObjectUtils.isEmpty(user))
        return ResponseResult.error().message("用户不存在");
        return ResponseResult.ok().data("userId",user.getUserId());
    }

    /**
     * 获取用户信息
     * @param userId
     * @return
     */
    @GetMapping("/getUserInfo/{username}")
    public ResponseResult getUserInfo(@PathVariable String username){
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("user_name", username);
    User user = userService.getOne(queryWrapper);
        return ResponseResult.ok().data("userInfo",user);
    }

    /**
     * 修改个人信息
     * @param user
     * @return
     */
     @PutMapping("/updateUserInfo/{info}")
    public ResponseResult updateUserInfo(@RequestBody User user,@PathVariable String info){
         //修改用户名
         if(user.getUserName()!=null){
             QueryWrapper<User> queryWrapper=new QueryWrapper<>();
             queryWrapper.eq("user_name", user.getUserName());
             User user1 = userService.getOne(queryWrapper);
             if(!ObjectUtils.isEmpty(user1))
                 return ResponseResult.error().message("用户名已存在");
             UpdateWrapper<User> updateWrapper=new UpdateWrapper<>();
             updateWrapper.eq("user_name", info);
             userService.update(user, updateWrapper);
             return ResponseResult.ok().message("修改用户名成功");
         }
         //修改密码
         if(user.getUserPassword()!=null){
             String[] split = info.split("-");
             String name=split[0];
             String oldPassword=split[1];
             oldPassword = DigestUtils.md5DigestAsHex(oldPassword.getBytes(StandardCharsets.UTF_8));
             QueryWrapper<User> queryWrapper=new QueryWrapper<>();
             queryWrapper.eq("user_name", name);
             User user1 = userService.getOne(queryWrapper);
             if(!user1.getUserPassword().equals(oldPassword)){
                 return ResponseResult.error().message("原密码错误，请重新输入或前往登录界面重置密码");
             }
             user.setUserPassword(DigestUtils.md5DigestAsHex(user.getUserPassword().getBytes(StandardCharsets.UTF_8)));
             UpdateWrapper<User> updateWrapper=new UpdateWrapper<>();
             updateWrapper.eq("user_name", name);
             userService.update(user, updateWrapper);
             return ResponseResult.ok().message("修改密码成功");
         }
         UpdateWrapper<User> updateWrapper=new UpdateWrapper<>();
         updateWrapper.eq("user_name", info);
         userService.update(user, updateWrapper);
        return ResponseResult.ok().message("修改成功");
    }

    /**
     * 获取用户列表
     * @param page 页码
     * @param limit 数量
     * @return 用户列表
     */
    @GetMapping("/getUserList/{page}/{limit}")
    public ResponseResult getUserList(@PathVariable Long page,@PathVariable Long limit){
        Map<String, Object> users = userService.getUsers(page, limit);
        return ResponseResult.ok().data(users);
    }

    /**
     * 冻结账户
     * @param userId 账户id
     * @return
     */
    @PutMapping("/freezeAccount/{userId}")
    public ResponseResult freezeAccount(@PathVariable String userId){
        UpdateWrapper<User> updateWrapper=new UpdateWrapper<>();
        updateWrapper.eq("user_id",userId).set("user_freeze", 1);
         if(userService.update(updateWrapper)){
             return ResponseResult.ok().message("冻结成功");
         }
        return ResponseResult.error().message("冻结失败");
    }

    /**
     * 解冻账户
     * @param userId 账户id
     * @return
     */
    @PutMapping("/unFreezeAccount/{userId}")
    public ResponseResult unFreezeAccount(@PathVariable String userId){
        UpdateWrapper<User> updateWrapper=new UpdateWrapper<>();
        updateWrapper.eq("user_id",userId).set("user_freeze", 0);
        if(userService.update(updateWrapper)){
            return ResponseResult.ok().message("解冻成功");
        }
        return ResponseResult.error().message("解冻失败");
    }

    /**
     * 根据用户id或名称或email获取用户信息
     * @param eONOE
     * @return
     */
    @GetMapping("/searchUserInfo")
    public ResponseResult searchUser(@RequestParam String eNOE){
        Map<String, Object> userInfo = userService.getUserInfo(eNOE);
        if(ObjectUtils.isEmpty(userInfo.get("user"))){
            return ResponseResult.error().message("用户不存在,请核对输入信息");
        }
        return ResponseResult.ok().data(userInfo);
    }

    /**
     * 用户权限修改
     * @param userId
     * @param role
     * @return
     */
    @PutMapping("/updateRole/{userId}/{role}")
    public ResponseResult updateRole(@PathVariable String userId, @PathVariable String role){
        UpdateWrapper<UserRole> updateWrapper=new UpdateWrapper<>();
        updateWrapper.set("role_id",UserType.valueOf(role)).eq("user_id", userId);
        if(roleService.update(updateWrapper)){
            return ResponseResult.ok().message("修改权限成功");
        }
        return ResponseResult.error().message("修改权限失败");
    }
}
